package com.billdowney.security.handler;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import com.billdowney.dao.user.UserLoginInfoDao;
import com.billdowney.entity.user.UserInfo;
import com.billdowney.entity.user.UserLoginInfo;
import com.billdowney.entity.user.UserLoginRecordStatus;
import com.billdowney.service.impl.base.BaseServiceImpl;
import com.billdowney.service.interfaces.system.log.SystemLogService;
import com.billdowney.service.interfaces.user.UserLoginRecordService;
import com.billdowney.util.http.HttpIOUtil;
import com.billdowney.util.log.SystemLogHandleType;
import com.billdowney.util.request.RequestUtil;
import com.billdowney.util.return_type.ReturnData;

/**
 * 自定义security成功处理类
 * 
 * @author 超级小富翁 - BillDowney
 * @date 2019年2月7日 上午11:34:27
 */
@Service
public class LoginSuccessHandler extends BaseServiceImpl<UserLoginInfoDao, UserLoginInfo, String>
		implements AuthenticationSuccessHandler {

	@Autowired
	private UserLoginRecordService loginRecordService;
	@Autowired
	private SystemLogService systemLogService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		try {
			// 如果属于用户登陆信息类
			if (authentication.getPrincipal() instanceof UserLoginInfo) {
				UserLoginInfo userLoginInfo = (UserLoginInfo) authentication.getPrincipal();
				loginRecordService.addUserLoginRecord(request, userLoginInfo, UserLoginRecordStatus.userLogin);
				HttpIOUtil.outJsonData(response, new ReturnData(userLoginInfo.getUserInfo()));
			}
			// 如果属于临时用户登陆
			else if (authentication.getPrincipal() instanceof User) {
				User user = (User) authentication.getPrincipal();
				UserInfo userInfo = new UserInfo();
				userInfo.setId("1");
				userInfo.setNickname(user.getUsername());
				HttpIOUtil.outJsonData(response, new ReturnData(userInfo));
				systemLogService.save("使用临时账户登陆：" + user.getUsername(), SystemLogHandleType.common, getClass(),
						RequestUtil.getIpAddr(request), null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			HttpIOUtil.outJsonData(response, new ReturnData(e));
		}
	}

	@Resource(type = UserLoginInfoDao.class)
	@Override
	public void setDao(UserLoginInfoDao userLoginInfoDao) {
		super.dao = userLoginInfoDao;
	}

}
